<template>
	<div>
		<div class="search">
			<!-- v-model 与数据双向绑定 -->
			<input v-model="keyword" class="search-input" type="text" placeholder="输入城市名或拼音" />
		</div>
		<!-- 没有改变的数据不需要v-bind动态绑定 keyword为空时，该div不显示 -->
		<div class="search-content" ref="search" v-show="keyword">
			<ul>
				<li
					class="search-item border-topbottom"
					v-for="item of list"
					:key="item.id"
					@click="handleCityClick(item.name)"
				>{{item.name}}</li>
				<li class="search-item border-topbottom" v-show="hasNodata">没有找到匹配数据</li>
			</ul>
		</div>
	</div>
</template>


<script>
import {mapMutations} from 'vuex'
import Bscroll from 'better-scroll'

export default {
  name: "CitySearch",
  props:{
    cities:Object
  },
  data() {
    return {
      keyword:'',
      list:[],
      timer:null
    }
  },
  methods: {
    handleCityClick(city){
      // this.$store.commit('changeCity',city)
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  watch: {
    keyword(){
      if (this.timer) {
        clearTimeout(this.timer)
      }
      // 当keyword为空时，返回空
      if (!this.keyword) {
        this.list = []
        return
      }

      // 定义节流器
      this.timer = setTimeout(() => {
        // 定义一个空数组获取for循环得出的数据
        const result = []
        for (let i in this.cities){
          // 通过forEach传入参数，通过indexOf匹配传值是否相等，相等返回值1与-1对比，通过则将数据push到result数组里
          this.cities[i].forEach((value)=>{
            if (value.spell.indexOf(this.keyword)> -1 ||value.name.indexOf(this.keyword)>-1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100);
    }
  },
  computed: {
    // 定义一个计算属性，决定没有找到数据后显示什么,记得加this
    hasNodata(){
      return !this.list.length
    }
  },
  mounted() {
    // 给Bscroll传一个实例，同时将ref绑定的search 传回一个DOM元素，使得Bscroll滚动生效
    this.scroll = new Bscroll(this.$refs.search)
  },
};
</script>



<style lang="stylus" scoped>
@import '~styles/varibles.styl';

.search {
  height: 0.72rem;
  padding: 0.1rem;
  background: $bgColor;

  .search-input {
    box-sizing: border-box;
    height: 0.62rem;
    padding: 0.1rem;
    width: 100%;
    line-height: 0.62rem;
    text-align: center;
    border-radius: 0.06rem;
    color: #666;
  }
}

.search-content {
  z-index: 1;
  overflow: hidden;
  position: absolute;
  top: 1.68 rem;
  left: 0;
  right: 0;
  bottom: 0;
  background: #eee;

  .search-item {
    line-height: 0.62rem;
    padding-left: 0.2rem;
    color: #666;
    background: #fff;
  }
}
</style>